package com.lzy.wzy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

@Configuration
public class OtherConfig {

    @Bean
    public Key key() {
        KeyGenerator keyGenerator;
        Key key = null;
        try {
            keyGenerator = KeyGenerator.getInstance("AES");
            String secret = "lzy_wzy_secret";
            keyGenerator.init(new SecureRandom(secret.getBytes()));
            SecretKey secretKey = keyGenerator.generateKey();
            byte[] byteKey = secretKey.getEncoded();
            key = new SecretKeySpec(byteKey, "AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return key;
    }

    @Bean
    public Cipher cipherEncode() {
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return cipher;
    }

    @Bean
    public Cipher cipherDecode() {
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return cipher;
    }


}
